<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :ok-button-props="{ props: { disabled: disableSubmit } }"
    :fullscreen="true"
    @close="close"
    cancelText="关闭"
  >
    <template slot="footer">
      <a-button key="back" style="padding-left: 8px; padding-right: 8px" @click="close(false)"> 关闭</a-button>
      <template v-if="!Loading && !isCheck">
        <a-button v-if="!disableSubmit && saveOperate == '1'" key="save" style="padding-left: 8px; padding-right: 8px" :disabled="disableSubmit" @click="temporarySave()"> 暂存</a-button>
        <a-popconfirm v-if="!disableSubmit && saveOperate == '1'" title="确定提交吗?" @confirm="() => saveOrSubmit()">
          <a-button key="save" style="padding-left: 8px; padding-right: 8px" :disabled="disableSubmit"> 提交</a-button>
        </a-popconfirm>
        <a-button v-if="!disableSubmit && saveOperate == '2'" key="save" style="padding-left: 8px; padding-right: 8px" :disabled="disableSubmit" @click="saveOrSubmit()"> 保存</a-button>
        <a-divider type="vertical"/>
        <a-button
          key="submit"
          type="primary"
          style="padding-left: 8px; padding-right: 8px"
          v-if="!isApprove"
          v-permission="['40010']"
          :disabled="(disableSubmit || !isAllPassed) && model.operateState != '4' && (model.state == '1' || model.state == '2')"
          @click="close(true)"
        >
          提交审批
        </a-button>
        <template v-if="isApprove">
          <a-button
            :disabled="model.state != '1'"
            v-permission="['40020']"
            @click="setApproveReason('9')"
            style="padding-left: 8px; padding-right: 8px"
          >
            同意
          </a-button>
          <a-button
            :disabled="model.state != '1'"
            v-permission="['40020']"
            type="danger"
            @click="setApproveReason('1')"
            style="padding-left: 8px; padding-right: 8px"
          >
            拒绝
          </a-button>
        </template>
      </template>
    </template>

    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="8">
            <a-form-item label="是否通过审核">
              <j-dict-select-tag
                style='width: 100%'
                placeholder="请选择"
                v-model="queryParam.sftgsh"
                dict-code="yes_no" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="内容">
              <a-input placeholder="请输入" v-model="queryParam.contents"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" style="margin-left: 8px" icon="reload">清除条件</a-button>
              <a-upload
                v-if="saveOperate == '1' && !isCheck && !disableSubmit"
                name="file"
                :showUploadList="false"
                :multiple="false"
                :data="queryParam"
                :headers="tokenHeader"
                :action="url.importExcelUrl"
                accept=".xlsx, .xls"
                @change="handleImportExcel">
                <a-button type="primary" style="margin-left: 8px" icon="import">导入
                </a-button>
              </a-upload>
              <a-button type="primary" style="margin-left: 8px" icon="download" @click="OnExportList">导出</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <a-spin :spinning="Loading">
      <div :class="{ isCheck: isCheck }">
        <a-table
          rowKey="id"
          class="edit-list"
          ref="table"
          size="middle"
          bordered
          width="100vw"
          :pagination="false"
          :columns="columns"
          :dataSource="dataSource"
          :rowClassName="tableRowClass"
          :scroll="{ x: 250, y: 520 }"
          :customRow="handleClickRow"
        >
          <div slot="title">
            <div class="title">审计发现问题整改跟踪情况表</div>
          </div>
          <template slot="rowIndex">
            <div class="header-title">
              <div style="position: absolute; top: 95px; left: -28px">序号</div>
              <div style="position: absolute; top: 18px; left: 0; width: 30px">内容</div>
              <div
                style="
                  content: '';
                  position: absolute;
                  width: 1px;
                  height: 160px;
                  top: -10px;
                  left: 0;
                  background-color: rgb(200 207 211);
                  display: block;
                  transform: rotate(330deg);
                  box-sizing: border-box;
                "
              />
            </div>
          </template>
          <template v-for="itemNormal in normalCell" v-slot:[itemNormal]="text, record">
<!--            <j-ellipsis :value="record[itemNormal]" :length="15" />-->
            <div :title="record[itemNormal]" style="width: 100%; height: 45px; overflow-x: hidden; overflow-y: auto">{{ record[itemNormal] }}</div>
          </template>
          <template v-for="itemInput in inputCell" v-slot:[itemInput]="text, record">
            <a-input
              :key="itemInput"
              class="normalInput"
              v-if="!disableSubmit && saveOperate == '1' && !isCheck"
              :disabled="disableSubmit || record.sftgsh != '0'"
              v-model="record[itemInput]"
            />
            <span v-else><j-ellipsis :value="record[itemInput]" :length="15" /></span>
          </template>
          <template v-for="itemMoney in moneyCell" v-slot:[itemMoney]="text, record">
            <a-input-number
              v-if="!disableSubmit && saveOperate == '1' && !isCheck"
              class="inputnumber"
              :key="itemMoney"
              :precision="2"
              :disabled="disableSubmit || record.sftgsh != '0'"
              @change="handleChange(record, itemMoney)"
              v-model="record[itemMoney]"
            />
            <span v-else>{{ record[itemMoney] }}</span>
          </template>
          <template v-for="itemCount in countCell" v-slot:[itemCount]="text, record">
            <a-input-number
              v-if="!disableSubmit && saveOperate == '1' && !isCheck"
              class="inputnumber"
              :key="itemCount"
              :precision="0"
              :min="0"
              :disabled="disableSubmit || record.sftgsh != '0'"
              @change="handleChange(record, itemCount)"
              v-model="record[itemCount]"
            />
            <span v-else>{{ record[itemCount] }}</span>
          </template>
          <template slot="zgztzgsj" slot-scope="text, record">
            <a-date-picker
              v-if="!disableSubmit && saveOperate == '1' && !isCheck"
              style="width: 100%"
              :disabled="disableSubmit || record.sftgsh != '0'"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              v-model="record['zgztzgsj']"
            />
            <span v-else>{{ record['zgztzgsj'] }}</span>
          </template>
          <template v-for="itemTotal in totalCell" v-slot:[itemTotal]="text, record">
            <span class="spancell">{{ record[itemTotal] }}</span>
          </template>
          <template slot="sftgsh" slot-scope="text, record">
            <a-switch
              checked-children="是"
              un-checked-children="否"
              :disabled="disableSubmit || saveOperate != '2'"
              :checked="text=='1'"
              @change="shChange({ $event, record })"
            />
          </template>
          <template slot="shryj" slot-scope="text, record">
            <a-input
              class="normalInput"
              v-if="!disableSubmit && saveOperate == '2' && !isCheck"
              :disabled="disableSubmit || saveOperate != '2'"
              v-model="record['shryj']"
            />
            <span v-else><div :title="text" style="width: 100%; height: 45px; overflow-x: hidden; overflow-y: auto">{{ text }}</div></span>
          </template>
        </a-table>
      </div>
    </a-spin>
    <SelectApprove ref="approver" :id="model.id" @submitData="handleSubmit"></SelectApprove>
    <SetReason ref="setReason" @approveReason="approveData"></SetReason>
  </j-modal>
</template>
<script>
import columns from './FactTableViewColumns'
import { getAction, putAction } from '@/api/manage'
import store from '@/store'
import SelectApprove from '@views/sj/sjxmzygl/commView/public/SelectApprover.vue'
import SetReason from '@views/sj/sjxmzygl/commView/public/SetReason.vue'
import { butStatus } from '@views/sj/sjxmzygl/butStatus'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { Modal } from 'ant-design-vue'
import viewTypeId from '@views/sj/sjxmzygl/commView/public/typeId'
import { WORK_AUTH } from '@/store/mutation-types'

export default {
  name: 'FactTableView',
  components: { SetReason, SelectApprove },
  mixins: [butStatus, JeecgListMixin],
  data() {
    return {
      viewTypeId: viewTypeId,
      typeId: viewTypeId['审计问题整改'],
      currentRow: {},
      userInfo: store.getters.userInfo,
      departInfo: store.getters.departInfo,
      Loading: false,
      disableSubmit: false,
      title: '',
      visible: false,
      isCheck: false,
      isApprove: false,
      columns: columns(this),
      model: {},
      queryParam: {},
      superParam: {},
      dataSource: [],
      saveOperate: null, // 1 反馈  2 审核
      approveId: '',
      url: {
        list: '/sjxmzygl/sjListRectification/queryNoPageList',
        edit: '/sjxmzygl/sjListRectification/edit',
        getCreatData: '/sjxxzhgl/sjProjectReport/projectInitData',
        add: '/sjxxzhgl/sjProjectReport/add',
        getPeople: '/sys/user/queryUserByDepId',
        submitData: '/common/sjProcCommon/reportShen',
        importExcelUrl: `${window._CONFIG['domianURL']}/sjxmzygl/sjListRectification/importExcel`,
        exportList: '/sjxmzygl/sjListRectification/exportRectificationList',
        submit: '/sjxmzygl/sjWorkUsers/submitAudit',
        permission: '/sys/permission/getButtonByUser',
        approve: '/common/sjProcCommon/zyApplyCommit'
      },
      normalCell: [
        'proName',
        'sjbgmc',
        'bgwh',
        'bgdygx',
        'bsjdwName',
        'wtnr',
        'dingxing',
        'dxyj',
        'zrjd',
        'zgjy'
      ],
      inputCell: [
        'wzjy',
        'zgdbbm',
        'xjdw',
        'zgcssxzg',
        'zgcsjyfszg',
        'zgcsytzg',
        'zgztzgzt',
        'zgztzgyy',
        'zgztxybzgcs',
        'wzclzzwzwjh',
        'wzclzzwzwjmc',
        'zczlmc',
        'shryj',
        'bz'
      ],
      moneyCell: [
        'sjzgcxtzkjzm',
        'sjzgcxshzj',
        'sjzgcxwhss',
        'sjzgcxghyzjqd',
        'sjzgcxsjcz',
        'sjzgcxbjsf',
        'sjzgcxqtcx',
        'wzclkjxchjjcf'
      ],
      countCell: [
        'sjzgcxfxdws',
        'sjzgcxfxzd',
        'sjzgcxfyhwsywlc',
        'sjzgcxfqt',
        'zgjytc',
        'zgjycn',
        'qdzzwzwgjytzzrzjwtxs',
        'qdzzwzxsfjgyshbgajxs',
        'wzclgyjjcf',
        'wzclgydjcf',
        'wzclgyzwcf',
        'wzclgyzzcl',
        'wzclkjxc',
        'wzclyssfjgsary'
      ],
      totalCell: [
        'sjzgcxhj',
        'sjzgcxfhj'
      ],

      calculateCell: [
        { 'sjzgcxhj': ['sjzgcxtzkjzm', 'sjzgcxshzj', 'sjzgcxwhss', 'sjzgcxghyzjqd', 'sjzgcxsjcz', 'sjzgcxbjsf', 'sjzgcxqtcx'] },
        { 'sjzgcxfhj': ['sjzgcxfxdws', 'sjzgcxfxzd', 'sjzgcxfyhwsywlc', 'sjzgcxfqt'] }
      ]
    }
  },
  created() {
  },
  computed: {
    isAllPassed() {
      return this.dataSource.length == 0 || this.dataSource.every(item => item.sftgsh == '1')
    }
  },
  methods: {
    check(record) {
      this.model = {}
      this.model = record
      this.queryParam = {}
      this.queryParam.proId = this.model.id
      this.superParam.proId = this.model.id
      this.dataSource = []
      this.getList()
    },
    edit(record) {
      this.model = {}
      this.model = record
      this.queryParam = {}
      this.queryParam.proId = this.model.id
      this.superParam.proId = this.model.id
      this.dataSource = []
      this.getWorkAuth()
      this.getList()
    },
    getList() {
      this.visible = true
      this.Loading = true
      getAction(this.url.list, { proId: this.model.id }).then((res) => {
        if (res.success) {
          this.dataSource = res.result
        } else {
          this.$message.error(res.message)
          this.visible = false
        }
      }).finally(() => {
        this.Loading = false
      })
    },
    handleClickRow(record, index) {
      return {
        on: {
          click: () => {
            if (!this.disableSubmit) {
              this.currentRow = record
            }
          }
        }
      }
    },
    tableRowClass(record) {
      if (record.id == this.currentRow.id) {
        return 'rowClass'
      } else if (this.isDateGreaterThanNow(record.zgztzgsj)) {
        return 'rowClassRed'
      }
      return ''
    },

    close(isSubmit) {
      // 判断是否都通过审核
      if (isSubmit && !this.isAllPassed) {
        this.$message.error('存在未通过审核的数据，请先审核！')
      } else {
        this.currentRow = {}
        if (isSubmit) {
          this.$refs.approver.showApproveConfirm = true
        } else {
          this.visible = false
        }
      }
    },

    handleSubmit(userId) {
      let that = this
      if (this.saveOperate) {
        putAction(this.url.edit, {
          rectificationVoList: this.dataSource,
          operate: this.saveOperate
        }).then((res) => {
          if (res.success) {
            getAction(that.url.submit, {
              proId: that.model.id,
              userId: userId,
              typeId: that.typeId
            }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.close()
                that.$emit('ok')
              } else {
                that.$message.error(res.message)
              }
            })
          } else {
            this.$message.error(res.message)
          }
        })
      } else {
        this.$message.error('状态异常，请刷新重试！')
      }
    },

    temporarySave(){
      if (this.saveOperate) {
        putAction(this.url.edit, {
          rectificationVoList: this.dataSource,
          operate: '0'  // 0暂存，1：反馈保存、2：审核保存
        }).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('ok')
          } else {
            this.$message.error(res.message)
          }
        })
      } else {
        this.$message.error('状态异常，请刷新重试！')
      }
    },

    // 保存或提交
    saveOrSubmit() {
      if (this.saveOperate) {
        putAction(this.url.edit, {
          rectificationVoList: this.dataSource,
          operate: this.saveOperate
        }).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.close()
            this.$emit('ok')
          } else {
            this.$message.error(res.message)
          }
        })
      } else {
        this.$message.error('状态异常，请刷新重试！')
      }
    },
    // 计算合计
    handleChange(row, col) {
      // 提前构建字段到汇总字段的映射
      const fieldToKeyMap = {}
      this.calculateCell.forEach(item => {
        for (let key in item) {
          item[key].forEach(field => {
            fieldToKeyMap[field] = key
          })
        }
      })
      if (fieldToKeyMap[col]) {
        const key = fieldToKeyMap[col]
        const targetItem = this.calculateCell.find(item => item[key])
        const fields = targetItem[key]
        row[key] = fields.reduce((total, field) => {
          return total + (parseFloat(row[field]) || 0)
        }, 0)
      }
    },
    shChange({ $event, record }) {
      this.$set(record, 'sftgsh', $event ? '1' : '0')
    },

    handleImportExcel(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
          this.dataSource = []
          this.getList()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`)
        }
      } else if (info.file.status === 'error') {
        if (info.file.response.status === 500) {
          const data = info.file.response
          const token = Vue.ls.get(ACCESS_TOKEN)
          if (token && data.message.includes('Token失效')) {
            Modal.error({
              title: '登录已过期',
              content: '很抱歉，登录已过期，请重新登录',
              okText: '重新登录',
              mask: false,
              onOk: () => {
                store.dispatch('Logout').then(() => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  window.location.reload()
                })
              }
            })
          }
        } else {
          this.$message.error(`文件上传失败: ${info.file.msg} `)
        }
      }
    },

    getWorkAuth() {
      this.Loading = true
      getAction(this.url.permission, { proId: this.model.id }).then((res) => {
        if (res.success) {
          let workAuthData = res.result.workButtonAuth
          sessionStorage.setItem(WORK_AUTH, JSON.stringify(workAuthData))
          this.Loading = false
        }
      })
    },
    isDateGreaterThanNow(dateStr){
      if (!dateStr || isNaN(Date.parse(dateStr))) {
        return false;  // 如果为空或者不是有效的日期格式，返回false
      }

      const currentDate = new Date();
      const inputDate = new Date(dateStr);

      return inputDate > currentDate;
    }
  }
}
</script>

<style lang='less' scoped>
@import './FactTableView.less';

.edit-list {
  .header-title {
    height: 135px;
    text-align: center;
  }
}

.table-header {
  margin-bottom: 10px;

  .table-title {
    font-weight: bold;
    margin-left: 15px;
  }
}

.tableHiddle {
  display: none;
}

.tableShow {
  display: block;
}
</style>
